(() => {
  //将字符串时间转换为毫秒,1秒=1000毫秒
  const getMsec = (str) => {
    var timeNum = str.substring(0, str.length - 1) * 1; //时间数量
    var timeStr = str.substring(str.length - 1, str.length); //时间单位后缀，如h表示小时
    if (timeStr == "s") {
      //20s表示20秒
      return timeNum * 1000;
    } else if (timeStr == "h") {
      //12h表示12小时
      return timeNum * 60 * 60 * 1000;
    } else if (timeStr == "d") {
      return timeNum * 24 * 60 * 60 * 1000;
    } //30d表示30天
  };
  class LocalCookie {
    constructor(options) {
      if (options) {
        if (options.time) this.time = options.time;
        if (options.domain) this.domain = options.domain;
      }
      if (options && options.storeName) {
        this.dataStoreName = options.storeName;
      }
      this.set(this.dataStoreName, { data: options.data || {} });
      return this;
    }
    time = "1d";
    domain = "/";
    dataStoreName = DEFAULT_STORENAME;
    get(name) {
      var arr,
        reg = new RegExp("(^| )" + this.dataStoreName + "=([^;]*)(;|$)"); //正则匹配
      if ((arr = document.cookie.match(reg))) {
        let res = JSON.parse(decodeURIComponent(arr[2]));
        if (res) {
          return name ? res.data[name] : res.data;
        }
      } else {
        return null;
      }
    }
    set(name, value, time) {
      var msec = getMsec(time || this.time); //获取毫秒
      var exp = new Date();
      exp.setTime(exp.getTime() + msec * 1);
      let res = this.get(this.dataStoreName);
      if (res) {
        res.data[name] = value;
        res.time = time;
        document.cookie =
          this.dataStoreName +
          "=" +
          encodeURIComponent(JSON.stringify(res)) +
          ";expires=" +
          exp.toGMTString() +
          ";path=" +
          this.domain;
      }
      return this;
    }
    update(data) {
      let res = this.get(this.dataStoreName);
      if (res) {
        res.data = Object.assign(res.data, data);
        this.set(this.dataStoreName, res, res.time);
      }
      return this;
    }
    remove(name) {
      let exp = new Date();
      exp.setTime(exp.getTime() - 1);
      const value = this.get(name);
      if (value != null) {
        document.cookie =
          name +
          "=" +
          encodeURIComponent(JSON.stringify(value)) +
          ";expires=" +
          exp.toGMTString() +
          ";path=" +
          this.domain;
      }
      return this;
    }
    clear() {
      let res = this.get(this.dataStoreName);
      if (res) {
        this.set(this.dataStoreName, { data: {} }, res.time);
        return this;
      } else {
        return;
      }
    }
  }
})();
